import { createRouter, createWebHistory } from 'vue-router'
import erpRoutes from './modules/erp'
import { hasPerm } from '@/utils/permission'
import { useUserStore } from '@/store/user'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    ...erpRoutes,
    { 
      path: '/login', 
      name: 'Login', 
      component: () => import('@/views/login/index.vue'), 
      meta: { public: true } 
    }
  ]
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  
  // 如果是登录页面或公开页面，直接放行
  if (to.path === '/login' || to.meta.public) {
    return next()
  }
  
  // 如果没有token，跳转到登录页
  if (!userStore.token) {
    return next('/login')
  }
  
  // 检查页面权限
  if (to.meta && to.meta.perm && !hasPerm(to.meta.perm)) {
    return next('/403')
  }
  
  next()
})

export default router
